Skip to content

Do not narrow a comparison operand whose counterpart can be NAN - #7058

Merged
staabm merged 4 commits into
phpstan:2.3.xfrom
zonuexe:nan-comparison-narrowing
Nov 14, 2026
Merged

staabm merged 4 commits into
phpstan:2.3.xfrom
zonuexe:nan-comparison-narrowing

Conversation

@zonuexe

@zonuexe zonuexe commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

BinaryOpHandler narrows both operands of <, <=, > and >= in the false branch. It keeps NAN on the side it narrows, but it still narrows each side as if the other one were ordered. This PR narrows a side only when the other side cannot be NAN.

Impact

Every ordering comparison with NAN is false, so the false branch of one tells nothing about the side opposite a NAN operand.

Expression Before After
-1|-2 $n, after if (NAN >= $n) return; *NEVER* -2|-1
int $i, after if ($i < NAN) return; int<0, max> int
int<-5, -1> $r → max(NAN, $r) NAN NAN|int<-5, -1>
int $i → max(NAN, $i) NAN|int<1, max> NAN|int
  • In the budget() reproducer of the issue, $ratio * $total can be 0.0 * INF, which is NAN. $used < NAN is false for every $used, so $used = -5 reaches the refund branch, but PHPStan narrowed $used to int<0, max> and reported the next comparison as Comparison operation "<" between int<0, max> and 0 is always false.
  • In root(), sqrt(-0.5) is NAN, so $n = 3 gets past the early return, but PHPStan narrowed $n to int<min, 0>.
  • With a literal NAN on the other side this already happened before float ranges. Since Add FloatRangeType for float<min, max> #6937, arithmetic and sqrt() infer types like NAN|float<0.0, max>, so code without a NAN literal reaches it.
  • Type min() / max() of two arguments as the union of both comparison orders #7050 typed min() / max() of two arguments as the union of both comparison orders, and left the cases where an operand is not a literal to this. max(NAN, $r) now follows from the comparison, as it already did for literals.
  • A side whose counterpart cannot be NAN is narrowed as before, so a comparison against an integer, a float range, a literal or a float after is_nan() keeps its precision. No existing test expectation changes.

The same assumption of a total order sits in the rewrite of a count() comparison, which this PR fixes in a second commit.

Expression, $root is NAN|float<0.0, 1.0> Before After
$root after if (count($a) < $root) return; float<0.0, 1.0> NAN|float<0.0, 1.0>
$root after if (strlen($s) <= $root) return; float<0.0, 1.0> NAN|float<0.0, 1.0>
$root in the true branch of count($a) < $root NAN|float<5.0E-324, 1.0> float<5.0E-324, 1.0>

Cause

The false branch of $a < $b has two ways to be reached by a NAN: $a is NAN, and $b is NAN. The narrowing covered the first one by adding NAN to the type it assigns to $a, which is why $a keeps NAN. It did not cover the second one: when $b is NAN the comparison is false whatever $a holds, so the false branch puts no bound on $a at all, and getGreaterOrEqualType() of a type that can be NAN is not a bound that holds. The same applies to $b with the sides swapped. > and >= delegate to < and <= with the operands swapped, so they follow.

count($a) < $x is specified as $x <= count($a) with the negated context, which the comment calls what a BooleanNot around the inverse operator would do. That holds only under a total order. For a NAN $x both comparisons are false, so the false branch of the first one is not the true branch of the second, and the narrowing of the true branch of $x <= count($a) dropped NAN from $x.

Fix

Each of the two narrowings in the false branch now runs only when the other operand cannot be NAN, and the count() rewrite is skipped whenever the other operand can be NAN, in every context, so that comparison takes the general path instead. The general path narrows each side on its own terms and keeps the bounds the rewrite used to give: in the true branch of count($a) < $root the count is still 0 for a $root below 1.0, and $root comes out without NAN, which a true ordering comparison does rule out. The narrowing of the true branch of an ordering comparison is otherwise unchanged, because it already rules out NAN on both sides. The native BinaryOpHandler in turbo-ext gets the same changes.

cannotBeNan() asks the question by removing NAN from the type and comparing: removing NAN from a type that cannot hold it leaves the type as it was. Asked as isSuperTypeOf() of the NAN constant, as FloatRangeType::accepts() does, never comes out as possibly NAN, because every type is a supertype of never.

Testing

tests/PHPStan/Analyser/nsrt/bug-15713.php covers the two reproducers from the issue, a literal NAN on either side, the min() / max() cases and the comparisons that keep narrowing. NumberComparisonOperatorsConstantConditionRuleTest::testBug15713() holds the errors the same file produces: the false positive is gone, and the comparison that really is always false is still reported.

The integration runs of drupal and glpi report one error more than their baseline allows, at Role.php:223 and Contract.php:1301. Both compare against a mixed operand, and the narrowing this PR removes used to remember that expression, which hid a second report of the same error. The new reports are correct. The count: of each entry lives in the analysed project's own baseline at the pinned ref, so this PR cannot adjust it.

Closes phpstan/phpstan#15713

Every ordering comparison with NAN is false, so the false branch of one tells nothing about the side opposite a NAN operand. The narrowing kept NAN on the side it narrowed, but still narrowed each side as if the other one were ordered, which turned a constant into never and cut ranges that the comparison leaves untouched.
The rewrite of count($a) < $x into $x <= count($a) with the negated context holds only under a total order: both comparisons are false for a NAN $x, so the false branch of the first one is not the true branch of the second, and it dropped NAN from $x.
Removing NAN from a type that cannot hold it leaves the type as it was. Asked as isSuperTypeOf() of the NAN constant, never came out as possibly NAN, because every type is a supertype of never. The count() rewrite skips a falsey context rather than only an exactly-false one, which keeps NAN out of the operand where the comparison is known not to be false.

@SanderMuller SanderMuller left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I compared the narrowing with real PHP 8.5. For 20 types I generated all 1,600 if ($a OP $b) pairs with <, <=, > and >=, and dumped both operands in both branches. The types include ints and int ranges, float, float ranges with and without NAN, NAN, 0.0|NAN, int|float, null, bool, int|null, float|null and strings. Then I checked each dumped type against the sample values that reach that branch in PHP.

  • On 94519e2, 102 branches have a type that misses a value that reaches them. All of them are false branches. On this PR there are none.
  • 176 dumped types change, all in a false branch, and every one gets wider.

Some of the wider types were already correct. When one operand is null or bool, PHP compares both sides as bools. NAN is then true, so it does not stop the order. For example, with ?int $a and float $f, the false branch of $a <= $f was int and is now int|null. null <= $f is true for every float, so int was right. This is only a loss of precision, and I am not sure it is worth a special case.

Two integration jobs are red because of this PR, and I think the new errors are correct. drupal and glpi each get one more occurrence of an error that their baseline already ignores:

  • drupal Role.php:223: $max > $role->weight ? $max : $role->weight + 1, where $max is mixed.
  • glpi Contract.php:1301: $next_alert[$type] after while ($next_alert[$type] < $previous_alert[$type]), where $previous_alert[$type] is mixed.

Before, the false branch narrowed the other operand against the mixed one and remembered that expression. That hid a second report of the same error. I reproduced both patterns. With an int or a string in place of the mixed operand, base and PR give the same errors.

The new nsrt file and testBug15713() fail without the change in BinaryOpHandler and pass with it. On 6896c23 I ran:

  • the full test suite with and without the Turbo extension, 23,771 tests each, all pass,
  • make phpstan and phpcs, both pass,
  • the Turbo smoke test, side-by-side.php, signature-parity.php and walk-trace.php, all pass,
  • the raw analysis output of the probe file and of bug-15713.php with Turbo on and off, which is identical.

I could not run make lint-turbo because clang-tidy 21 is not installed here, but "Turbo Extension Lint" is green in CI. The other red jobs are also red on #7050 or on the 2.3.x tip.

Performance: I analysed a file with 400 functions and about 5,200 ordering comparisons, 8 runs per side. Wall-clock times were noisy on this machine, so I compare user CPU. Without Turbo it is 6.65 s on 2.3.x and 6.84 s with this PR. With Turbo it is 2.51 s and 2.44 s, which is within the noise.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The inverse comparison rewrite loses count narrowing when the right operand can be NAN, requiring matching PHP and C++ fixes and a regression assertion for the true branch.

1 open issue
What changed in this PR

This PR corrects PHPStan’s comparison narrowing when an operand can be NAN, preventing false positives in ordering comparisons and improving inferred min()/max() types.

Changes:

  • Guard false-branch narrowing when the opposite operand can be NAN.
  • Adjust count and string-length comparison rewrites, with matching native implementation changes.
  • Add regression coverage for NAN comparisons and preserved narrowing.
File Description
turbo-ext/​src/​generated/​BinaryOpHandler.h Registers the native NAN-check helper.
turbo-ext/​src/​BinaryOpHandler.cpp Mirrors the PHP narrowing and rewrite guards.
tests/​PHPStan/​Rules/​Comparison/​NumberComparisonOperatorsConstantConditionRuleTest.php Checks expected comparison diagnostics for the regression fixture.
tests/​PHPStan/​Analyser/​nsrt/​bug-15713.php Covers NAN inference, comparison branches, and min()/max().
src/​Analyser/​ExprHandler/​BinaryOpHandler.php Adds NAN-aware guards to comparison narrowing and rewrites.

Review effort: Balanced

Comment on lines +379 to +380
!$context->falsey()
|| self::cannotBeNan($nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType())
Neither branch of count($a) < $x is a branch of $x <= count($a) when $x can be NAN, because both comparisons are false for a NAN. Restricting that to a falsey context left the true branch of the original computed as the false branch of the inverse, where the NAN guard then refused to narrow the count. The general path narrows each side on its own terms and keeps the bound.
@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the grid. 102 unsound branches down to none is the check I could not run myself.

I agree about null and bool, and I would leave it as it is. PHP compares both sides as bools when one of them is a bool or null, and NAN is true, so the order holds there. To keep that precision the guard would have to decide whether the comparison is a bool comparison before it asks whether the other operand can be NAN, which puts the comparison semantics into the narrowing. A wider type in a false branch is sound, so I would rather not pay that. It deserves its own issue if someone hits it.

The true branch did turn out to need work. The Copilot review found that the rewrite of a count() comparison dropped the narrowing of the count in the true branch, which PHPStan computes as the false branch of the inverse. I fixed it in a916e03 by skipping the rewrite in every context instead of a falsey one. The <= variant and preg_match() lost their bounds the same way. The general path restores all of them, and $root in the true branch now comes out without NAN, which beats the base.

The drupal and glpi reports are correct. I said so in the PR body: the count: of each entry sits in the analysed project's own baseline at the pinned ref, so this PR cannot touch it.

Mutation Testing went red with three escaped mutants on my guards and is green again. cannotBeNan() removes NAN from the type and compares, which also handles never. Ask it as isSuperTypeOf() of the NAN constant and never comes out as possibly NAN, because every type is a supertype of never.

Thanks for measuring the cost. Your numbers show the type test without the extension, 6.65 s against 6.84 s. On my file of 2,400 comparisons I measured 1.44 s against 1.38 s, so the result depends on how many comparisons reach the guard.

@SanderMuller SanderMuller left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-checked a916e03.

The count() rewrite now holds in both branches. I ran a second grid with count() and strlen() against the same 20 types, in both operand orders. That is 6,720 runtime checks: 324 unsound on the base and 0 on this head. Against 6896c23, all 56 changed types are true-branch narrowings, for example NAN|float<0.0, max> becomes float<0.0, max>. The new countBothBranches() assertions fail on the src of 6896c23, so the test covers the fix.

Agreed on null and bool.

The WordPress red is not from this PR. The red runs checked out WordPress at 24fa674, and the green runs on other PRs at 7924b71. The base reports the same three variable.undefined errors at 24fa674. The musl Turbo job could not pull alpine:3.24.

The full suite with and without the extension, phpstan, phpcs, lint-turbo, smoke, signature parity and walk-trace pass. The output is identical with the extension on and off on both grids. I timed a file of 2,400 count() and strlen() comparisons without the extension. User CPU was 4.93 s on the base and 4.76 s on this head.

@staabm
staabm merged commit 4ce4b19 into phpstan:2.3.x Nov 14, 2026
901 of 908 checks passed
@staabm

staabm commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The false branch of < and <= narrows the other operand even when the compared value can be NAN

4 participants